function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val)
    this.left = (left === undefined ? null : left)
    this.right = (right === undefined ? null : right)
}

function levelOrder(root) {
    const result = [];

    function traverse(node, level) {
        if (!node) return;

        // 如果当前层级的结果数组还不存在，创建一个
        if (!result[level]) {
            result[level] = [];
        }

        // 将节点值存入对应层级
        result[level].push(node.val);

        // 递归遍历左右子树，层级+1
        traverse(node.left, level + 1);
        traverse(node.right, level + 1);
    }

    traverse(root, 0);
    return result;
}

var sortedArrayToBST = function (nums) {
    let len = nums.length;
    let root = new TreeNode(nums[Math.floor(len / 2)]);
    let head = root;
    for (let i = Math.floor(len / 2) - 1; i >= 0; i--) {
        let node = new TreeNode(nums[i]);
        root.left = node;
        root = node;
    }
    root = head;

    for (let j = Math.floor(len / 2) + 1; j < nums.length; j++) {
        let node = new TreeNode(nums[j]);
        root.right = node;
        root = node;
    }
    return head;
};

// let nums = [-10, -3, 0, 5, 9];
let nums = [0, 1, 2, 3, 4, 5];
let result = levelOrder(sortedArrayToBST(nums));
console.log(result);


